package com.linkhub.oms.component.excel.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.linkhub.oms.common.enums.IEnumConvert;
import com.linkhub.oms.component.excel.annotation.CellPropertyMapping;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Description: CellEnumListIntegerConverter
 * @Author: echo
 * @Date: 2024/5/11 20:56
 * @Version: 1.0
 */
public class CellEnumListIntegerConverter implements Converter<List<Integer>> {
    @Override
    public Class<?> supportJavaTypeKey() {
        return List.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    @SuppressWarnings("all")
    public List<Integer> convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
                                           GlobalConfiguration globalConfiguration) throws Exception {


        String cellValue = cellData.getStringValue();
        Field field = contentProperty.getField();
        CellPropertyMapping mapping = field.getAnnotation(CellPropertyMapping.class);
        if (StringUtils.isBlank(cellValue) || Objects.isNull(mapping)) {
            return null;
        }

        String[] valueArr = cellValue.split(StringPool.COMMA);
        List<Integer> values = Stream.of(valueArr)
                .map(value -> (ExcelCellEnumConvert<String, Integer>)
                        IEnumConvert.valueOf(value, mapping.mappingEnum()))
                .filter(Objects::nonNull)
                .map(ExcelCellEnumConvert::getValue)
                .collect(Collectors.toList());

        return values;

    }


}
